﻿using PokerGame;
using Protocol.Code;

namespace Framework
{
    public class NetManager : ManagerBase
    {
        public static NetManager Instance;
        private ClientPeer client = new("127.0.0.1", 8999);
        private IHandler accoutHandler;
        private void Awake()
        {
            Instance = this;
            accoutHandler = new AccountHandler();
            Add(NetEvent.SEND_DTO, this);
        }
        private void Start()
        {
            client.Connect();
        }
        private void Update()
        {
            if (client == null) return;
            while (client.MessageQueue.Count > 0)
            {
                //接收网络消息并派发给对应的处理器
                SocketMessage message = client.MessageQueue.Dequeue();
                AssignedSocketMessage(message);
            }
        }
        public override void Execute(int eventCode, object message)
        {
            //将内部消息发送给服务器
            switch (eventCode)
            {
                case NetEvent.SEND_DTO:
                    client.Send(message as SocketMessage);
                    break;
                default:
                    break;
            }
        }

        public void Connected(string ip, int port)
        {
            client = new ClientPeer(ip, port);
        }

        /// <summary>
        /// 分派网络消息
        /// </summary>
        private void AssignedSocketMessage(SocketMessage message)
        {
            switch (message.OpCode)
            {
                case OpCode.ACCOUNT:
                    accoutHandler.OnReceive(message.SubCode, message.Value);
                    break;
                default:
                    break;
            }
        }
    }
}
